<?php
/**
 * Created by PhpStorm.
 * User: jinji
 * Date: 2017/10/22
 * Time: 23:10
 */

namespace App\Services;


use App\Model\Page;

class PageService
{
    public static function getPages()
    {
        $pages = Page::where('level',1)->orderBy('right','desc')->get();
        return $pages;
    }

    public static function catePages()
    {
        $start   = '2017-10-1';
        $current = time();
        $cates   = array();
       do{
           $end   = Util::getNextMonthDays($start)[0];
           $pages = Page::where('created_at','>',$start)->where('created_at','<',$end)->where('type',Page::TYPE_POST)->get();
           $date  = date('Y-m',strtotime($start));
           $cdate  = Util::chineseDate($date);
           array_push($cates,Util::array2Obj(array('time'=>$cdate,'date'=>$date,'count'=>$pages->count())));
           $start = $end;
           $pivot = strtotime($start);
       }while($pivot<$current);
       return $cates;
    }

    /**
     * 得到节点id的所有子节点
     * @param $id
     * @return array
     */
    public  function getChilds($id)
    {
        $pages = Page::where('type',Page::TYPE_PAGE)->get();
        $ids = $this->treeIds($pages,$id);
        return $ids;
    }

    public function getCates($id)
    {
        $pages = Page::where('type',Page::TYPE_PAGE)->orderBy('right','desc')->get();
        $childs = $this->getTree($pages,$id);
        return $childs;
    }

    private function treeIds($data, $pId)
    {
        static $ids = [];
        foreach ($data as $k => $v) {
            if ($v['parent'] == $pId) {
                $ids[] = $v['id'];
                $v['children'] = $this->treeIds($data, $v['id']);
            }
        }
        return $ids;
    }

    private function getTree($data, $pId)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['parent'] == $pId) {
                $v['children'] = $this->getTree($data, $v['id']);
                $tree[] = $v;
            }
        }
        return $tree;
    }
}